﻿// Copyright (c) ZhangPeihang. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using BootstrapBlazor.Components;
using LaserMark.Components.Components;
using LaserMark.Components.Events;
using LaserMark.Components.Layout;
using LaserMark.Components.Services;
using LaserMark.Components.Utils;
using LaserMark.Control.Service;
using LaserMark.Print.Service;
using Microsoft.AspNetCore.Components;
using Microsoft.Extensions.Localization;

namespace LaserMark.Components;
public partial class Header : IDisposable
{
    private string? HeaderClassString => CssBuilder.Default("ribbon-tab")
        .AddClass("border", true)
        .AddClassFromAttributes(AdditionalAttributes)
        .Build();

    private static string? GetClassString(RibbonTabItem item) => CssBuilder.Default()
        .AddClass("active", item.IsActive)
        .Build();

    [Inject]
    [NotNull]
    private IRibbonTabEventBus? EventBus { get; set; }

    [Inject]
    [NotNull]
    private IStringLocalizer<MainLayout>? Localizer { get; set; }

    [NotNull]
    private List<RibbonTabItem>? Items { get; set; } = new();

    [NotNull]
    private string? Icon { get; set; }

    [NotNull]
    private string? Text { get; set; }

    [Inject]
    [NotNull]
    private IGlobalStatus? GlobalStatus { get; set; }

    [NotNull]
    private bool IsRunning { get; set; }

    private bool IsStop { get; set; }

    private bool IsLimit { get; set; }

    private bool IsTimeout { get; set; }

    private bool IsScan { get; set; }

    private string? Message { get; set; }

    private bool IsZeroBack { get; set; }

    private bool IsShownProduct { get; set; }

    [Inject]
    [NotNull]
    private IControl? Control { get; set; }

    [Inject]
    [NotNull]
    private IPrint? Print { get; set; }

    private bool IsOff { get; set; }

    private bool IsOn { get; set; }

    private bool IsFirst { get; set; }

    protected override void OnInitialized()
    {
        base.OnInitialized();

        mc.GT_GetDi(0, mc.MC_GPI, out int value);
        var aa = Convert.ToString(value, 2).PadLeft(16);
        if (aa[12] == '1')
        {
            Text = "手动";
            Icon = "fa-solid fa-m";
        }
        else
        {
            Text = "自动";
            Icon = "fa-solid fa-a";
        }

        Items = new List<RibbonTabItem>()
            {
                new RibbonTabItem()
                {
                    Text = Localizer["Home"],
                    Items = new List<RibbonTabItem>()
                    {
                        new RibbonTabItem()
                        {
                            GroupName = "",
                            Template = BootstrapDynamicComponent.CreateComponent<Logo>().Render()
                        },
                        new RibbonTabItem()
                        {
                            GroupName = Localizer["ActionGroup"],
                            Command = RibbonTabConstants.ClearSts,
                            Icon = "fa-solid fa-bell",
                            Text = "清除报警"
                        },
                        new RibbonTabItem()
                        {
                            GroupName = Localizer["ActionGroup"],
                            Command = RibbonTabConstants.ZeroBack,
                            Icon = "fa-solid fa-rotate",
                            Text = Localizer["ZeroControl"]
                        },
                        new RibbonTabItem()
                        {
                            GroupName = Localizer["ActionGroup"],
                            Command = RibbonTabConstants.OnKeep,
                            Icon = "fa-solid fa-1",
                            Text = "单次"
                        },
                        new RibbonTabItem()
                        {
                            GroupName = Localizer["ActionGroup"],
                            Command = RibbonTabConstants.Run,
                            Icon = "fa-solid fa-play",
                            Text = Localizer["Run"]
                        },
                        new RibbonTabItem()
                        {
                            GroupName = Localizer["ActionGroup"],
                            Icon = "fa-solid fa-pause",
                            Text = Localizer["Pause"],
                            Command = RibbonTabConstants.Pause
                        },
                        new RibbonTabItem()
                        {
                            GroupName = Localizer["ActionGroup"],
                            Command = RibbonTabConstants.Stop,
                            Icon = "fa-solid fa-stop",
                            Text = Localizer["Stop"]
                        },
                        new RibbonTabItem()
                        {
                            Command = RibbonTabConstants.AutoOrManual,
                            GroupName = Localizer["ActionGroup"],
                            Icon = Icon,
                            IsDisabled = true,
                            Text = Text
                        },
                         new RibbonTabItem()
                        {
                            Command = RibbonTabConstants.OnlyTransfor,
                            GroupName = Localizer["ActionGroup"],
                            Icon = "fa-solid fa-arrow-up-from-bracket",
                            Text = "仅过渡"
                        },
                        new RibbonTabItem()
                        {
                            GroupName = Localizer["FileGroup"],
                            Icon = "fa-solid fa-globe",
                            Command = RibbonTabConstants.TaskList,
                            Text = "单机"
                        },
                        //new RibbonTabItem()
                        //{
                        //    GroupName = Localizer["FileGroup"],
                        //    Icon = "fa-solid fa-plus",
                        //    Text = Localizer["NewTemplate"],
                        //    Command = RibbonTabConstants.NewTemplate
                        //},
                        //new RibbonTabItem()
                        //{
                        //    GroupName = Localizer["FileGroup"],
                        //    Icon = "fa-solid fa-pen-to-square",
                        //    Text = Localizer["EditTemplate"],
                        //    Command = RibbonTabConstants.UpdaeteTemplate
                        //},
                        new RibbonTabItem()
                        {
                            GroupName = Localizer["FileGroup"],
                            Command = RibbonTabConstants.OpenFile,
                            Icon = "fa-solid fa-folder-open",
                            Text = Localizer["OpenFile"]
                        },
                         new RibbonTabItem()
                        {
                            GroupName = Localizer["FileGroup"],
                            Command = RibbonTabConstants.OpenFiles,
                            Icon = "fa-solid fa-folder-open",
                            Text = "批量导入"
                        },
                        new RibbonTabItem()
                        {
                            GroupName = Localizer["FileGroup"],
                            Command = RibbonTabConstants.SelectTemplate,
                            Icon = "fa-solid fa-folder-open",
                            Text = Localizer["UploadTemplate"]
                        },
                        new RibbonTabItem()
                        {
                            GroupName = Localizer["FileGroup"],
                            Command = RibbonTabConstants.Ezd3,
                            Icon = "fa-solid fa-object-group",
                            Text = "Ezcad3"
                        },
                        new RibbonTabItem()
                        {
                            GroupName = Localizer["SettingsGroup"],
                            Command = RibbonTabConstants.SystemSettings,
                            Icon = "fa-solid fa-gear",
                            Text = Localizer["SystemArgs"]
                        },
                        new RibbonTabItem()
                        {
                            GroupName = "其他",
                            Command = RibbonTabConstants.AuditLog,
                            Icon = "fa-solid fa-clock-rotate-left",
                            Text = "日志"
                        }
                    }
                }
            };
    }

    [NotNull]
    private CancellationTokenSource? Token { get; set; } = new();

    protected override void OnAfterRender(bool firstRender)
    {
        base.OnAfterRender(firstRender);

        if (firstRender)
        {
            _ = Task.Factory.StartNew(async () =>
            {
                var item = Items!.First(s => s.Text == "首页").Items.OfType<RibbonTabItem>().FirstOrDefault(s => s.Command == RibbonTabConstants.AutoOrManual);
                var item2 = Items!.First(s => s.Text == "首页").Items.OfType<RibbonTabItem>().FirstOrDefault(s => s.Command == RibbonTabConstants.ZeroBack);
                var item3 = Items!.First(s => s.Text == "首页").Items.OfType<RibbonTabItem>().FirstOrDefault(s => s.Command == RibbonTabConstants.ClearSts);

                var item4 = Items!.First(s => s.Text == "首页").Items.OfType<RibbonTabItem>().FirstOrDefault(s => s.Command == RibbonTabConstants.Run);
                var item5 = Items!.First(s => s.Text == "首页").Items.OfType<RibbonTabItem>().FirstOrDefault(s => s.Command == RibbonTabConstants.Pause);
                var item6 = Items!.First(s => s.Text == "首页").Items.OfType<RibbonTabItem>().FirstOrDefault(s => s.Command == RibbonTabConstants.Stop);
                var item7 = Items!.First(s => s.Text == "首页").Items.OfType<RibbonTabItem>().FirstOrDefault(s => s.Command == RibbonTabConstants.OnlyTransfor);
                while (Token is { IsCancellationRequested: false })
                {
                    try
                    {
                        mc.GT_GetDi(0, mc.MC_GPI, out int value);
                        var aa = Convert.ToString(value, 2).PadLeft(16);
                        if (aa[12] == '1')
                        {
                            item!.Text = "手动";
                            item.Icon = "fa-solid fa-m";
                            item2!.IsDisabled = false;
                            item3!.IsDisabled = false;

                            item4!.IsDisabled = true;
                            item5!.IsDisabled = true;
                            item6!.IsDisabled = true;
                            item7!.IsDisabled = false;
                        }
                        else
                        {
                            item!.Text = "自动";
                            item.Icon = "fa-solid fa-a";
                            item2!.IsDisabled = true;
                            item3!.IsDisabled = true;

                            item4!.IsDisabled = false;
                            item5!.IsDisabled = false;
                            item6!.IsDisabled = false;
                            item7!.IsDisabled = true;
                            if (item7!.IsActive)
                            {
                                item7.IsActive = false;
                                GlobalStatus.IsOnlyTransfor = false;
                            }
                        }

                        if (GlobalStatus.IsRunning)
                        {
                            await Control.GetDi(0, mc.MC_GPI, out value);
                            var status = Convert.ToString(value, 2).PadLeft(16, '0');
                            if (status[13] == '1')
                            {
                                IsRunning = false;
                                if (!IsStop)
                                {
                                    IsStop = true;
                                }
                            }
                            else
                                IsStop = false;
                            if (!IsRunning)
                                IsRunning = true;

                            IsScan = GlobalStatus.Iscan;
                            Message = GlobalStatus.ScanMesaage;
                            IsLimit = GlobalStatus.IsLimitY || GlobalStatus.IsLimitX || GlobalStatus.IsLimitZA || GlobalStatus.IsLimitZN;
                            IsTimeout = GlobalStatus.IsStateTimeOut;
                            IsZeroBack = !GlobalStatus.IsZZeroBack || !GlobalStatus.IsXZeroBack || !GlobalStatus.IsYZeroBack;
                            IsShownProduct = !string.IsNullOrEmpty(GlobalStatus.ProductMessage);
                            if (status[6] == '1')
                            {
                                IsOn = false;
                                if (!IsOff)
                                {
                                    IsOff = true;
                                    GlobalStatus.IsXZeroBack = false;
                                    GlobalStatus.IsYZeroBack = false;
                                    GlobalStatus.IsZZeroBack = false;
                                    mc.GT_SetDoBit(0, mc.MC_GPO, 1, 1);
                                    mc.GT_SetDoBit(0, mc.MC_GPO, 3, 1);
                                    mc.GT_SetDoBit(0, mc.MC_GPO, 4, 1);
                                    await Control.Stop(0, 1 << 8, 1 << 8);
                                    await Control.Stop(0, 1 << (2 - 1), 1 << (2 - 1));
                                    await Control.Stop(0, 1 << (3 - 1), 1 << (3 - 1));
                                    await Control.Stop(0, 1 << (4 - 1), 1 << (4 - 1));
                                    await Control.SetDoBit(0, mc.MC_GPO, 12, 1);
                                    await Control.SetDoBit(0, mc.MC_GPO, 8, 1);
                                    await Control.SetDoBit(0, mc.MC_GPO, 10, 1);
                                    await Control.AxisOff(0, 2);
                                    await Control.AxisOff(0, 3);
                                    await Control.AxisOff(0, 4);
                                }
                            }
                            else
                            {
                                IsOff = false;
                                if (!IsOn)
                                {
                                    IsOn = true;
                                    mc.GT_SetDoBit(0, mc.MC_GPO, 1, 0);
                                }
                            }
                        }

                        await InvokeAsync(StateHasChanged);
                        await Task.Delay(500);
                    }
                    catch (Exception ex)
                    {

                    }
                }
            });
        }
    }

    private static RenderFragment? RenderTemplate(RibbonTabItem item) => item.Component?.Render() ?? item.Template;

    private async Task OnItemClickAsync(RibbonTabItem item)
    {
        await EventBus.PublishAsync(new RibbonTabEventMessage(item));
    }

    public void Dispose()
    {
        GC.SuppressFinalize(this);
    }
}
